package org.gd.spring.batis;

import com.ibatis.sqlmap.client.SqlMapClient;

import java.sql.SQLException;

public class UserDaoIbatis implements UserDao {

    @Override
    public UserTEO addUser(UserTEO user, SqlMapClient sqlmapClient) {
        try {
            sqlmapClient.startTransaction();
            Integer id = (Integer)sqlmapClient.queryForObject("user.getMaxId");
            id = id == null ? 1 : id + 1;
            user.setId(id);
            user.setStatus(1);
            sqlmapClient.insert("user.addUser", user);
            user = getUserById(id, sqlmapClient);
            sqlmapClient.commitTransaction();
            return user;
        } catch(Exception e) {
            try {
                sqlmapClient.endTransaction();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public UserTEO getUserById(Integer id, SqlMapClient sqlmapClient) {
        try {
            return (UserTEO)sqlmapClient.queryForObject("user.getUserById", id);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void deleteUserById(Integer id, SqlMapClient sqlmapClient) {
        try {
            sqlmapClient.delete("user.deleteUserById", id);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
